package pe.edu.unmsm.pacis.shca.ams.agent;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import pe.edu.unmsm.pacis.shca.domain.entity.User;
import pe.edu.unmsm.pacis.shca.domain.message.GlobalMessage;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;

public class LoginAgent extends Agent {
	
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("serial")
	protected void setup() {

		// Login behaviour
		addBehaviour(new CyclicBehaviour(this) {
			@SuppressWarnings("rawtypes")
			public void action() {
				ACLMessage msg = receive();
				String content = "";
				GlobalMessage recep = null;
				Map map = null;
				if (msg != null) {
					System.out.println("");
					try {
						System.out.println(":::::::::::: Login Agent Recived: " + msg.getContentObject());
						recep = (GlobalMessage)msg.getContentObject();
						map = recep.getSend();
						Iterator itr = map.entrySet().iterator();
						while (itr.hasNext()) {
							Map.Entry e = (Map.Entry)itr.next();
							System.out.println("  Key: "+e.getKey()+"   Value:"+e.getValue());
						}
					} catch (UnreadableException e) {
						//e.printStackTrace();
					}
					
					content = ":: LocalName:" + myAgent.getLocalName() + " - Name:" + myAgent.getName();
					
					ACLMessage reply = msg.createReply();
					reply.setPerformative(ACLMessage.INFORM);
					reply.setContent(content);
					Map<String,Object> replyMsg = new HashMap<String, Object>();
					User user = new User();
					user.setLogin((String)map.get("login"));
					user.setName("Oscar");
					user.setLastName("Alvaro Aguilar");
					replyMsg.put("user", user);
					try {
						reply.setContentObject((Serializable) replyMsg);
					} catch (IOException e) {
						//e.printStackTrace();
					}
					send(reply);
					System.out.println(content);
					System.out.println("Finally");
					System.out.println("");
				} else
					block();
			}
		});

	}

	protected void takeDown() {
		try {
			DFService.deregister(this);
		} catch (Exception e) {
		}
	}
	
}
